package view;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.ResultSet;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.LineBorder;

import dao.BookDao;
import dao.BookTypeDao;
import model.Book;
import model.BookType;
import util.DbUtil;
import util.StringUtil;

public class BookAddInterFrm extends JInternalFrame {
    private JTextField bookNameTxt;
    private JTextField authorTxt;
    private final ButtonGroup buttonGroup = new ButtonGroup();
    private JTextField priceTxt;
    private JComboBox bookTypeJcb = new JComboBox();
    private JTextArea bookDescTxt = new JTextArea();
    private JRadioButton manJrb =null;
    private JRadioButton femaleJrb =null;

    private DbUtil dbUtil = new DbUtil();
    private BookTypeDao bookTypeDao = new BookTypeDao();
    private BookDao bookDao = new BookDao();

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    BookAddInterFrm frame = new BookAddInterFrm();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 初始化图书类别下拉框
     */
    private void fillBookType() {
        Connection con = null;
        BookType bookType = null;
        try {
            con = dbUtil.getCon();
            ResultSet rs = bookTypeDao.list(con, new BookType());
            while (rs.next()) {
                bookType = new BookType();
                bookType.setId(rs.getInt("id"));
                bookType.setBookTypeName(rs.getString("bookTypeName"));
                this.bookTypeJcb.addItem(bookType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * Create the frame.
     */
    public BookAddInterFrm() {
        setClosable(true);
        setIconifiable(true);
        setTitle("\u56FE\u4E66\u6DFB\u52A0");
        setBounds(100, 100, 603, 540);

        JLabel lblNewLabel = new JLabel("\u56FE\u4E66\u540D\u79F0\uFF1A");

        bookNameTxt = new JTextField();
        bookNameTxt.setColumns(10);

        JLabel label = new JLabel("\u56FE\u4E66\u4F5C\u8005\uFF1A");

        authorTxt = new JTextField();
        authorTxt.setColumns(10);

        JLabel label_1 = new JLabel("\u4F5C\u8005\u6027\u522B\uFF1A");

        manJrb = new JRadioButton("\u7537");
        manJrb.setSelected(true);
        buttonGroup.add(manJrb);

        femaleJrb = new JRadioButton("\u5973");
        buttonGroup.add(femaleJrb);

        JLabel label_2 = new JLabel("\u56FE\u4E66\u4EF7\u683C\uFF1A");

        priceTxt = new JTextField();
        priceTxt.setColumns(10);

        JLabel lblNewLabel_1 = new JLabel("\u56FE\u4E66\u7C7B\u522B\uFF1A");



        JLabel label_3 = new JLabel("\u56FE\u4E66\u63CF\u8FF0\uFF1A");



        JButton btnNewButton = new JButton("\u6DFB\u52A0");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    bookAddActionPerformed(e);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        btnNewButton.setIcon(new ImageIcon(BookAddInterFrm.class.getResource("/images/add.png")));

        JButton btnNewButton_1 = new JButton("\u91CD\u7F6E");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                resetValueActionPerformed(e);
            }
        });
        btnNewButton_1.setIcon(new ImageIcon(BookAddInterFrm.class.getResource("/images/reset.png")));
        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGap(48)
                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                        .addGroup(groupLayout.createSequentialGroup()
                                                .addComponent(btnNewButton)
                                                .addGap(44)
                                                .addComponent(btnNewButton_1)
                                                .addContainerGap())
                                        .addGroup(groupLayout.createSequentialGroup()
                                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                .addComponent(label_3)
                                                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                                                .addComponent(bookDescTxt))
                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
                                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                                .addComponent(lblNewLabel_1)
                                                                                .addPreferredGap(ComponentPlacement.UNRELATED)
                                                                                .addComponent(bookTypeJcb, 0, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                                .addComponent(lblNewLabel)
                                                                                .addPreferredGap(ComponentPlacement.RELATED)
                                                                                .addComponent(bookNameTxt, GroupLayout.PREFERRED_SIZE, 120, GroupLayout.PREFERRED_SIZE))
                                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                                .addComponent(label_1)
                                                                                .addGap(18)
                                                                                .addComponent(manJrb)
                                                                                .addGap(10)
                                                                                .addComponent(femaleJrb)))
                                                                .addGap(71)
                                                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
                                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                                .addComponent(label)
                                                                                .addGap(18)
                                                                                .addComponent(authorTxt, GroupLayout.PREFERRED_SIZE, 141, GroupLayout.PREFERRED_SIZE))
                                                                        .addGroup(groupLayout.createSequentialGroup()
                                                                                .addComponent(label_2)
                                                                                .addGap(18)
                                                                                .addComponent(priceTxt)))))
                                                .addContainerGap(65, Short.MAX_VALUE))))
        );
        groupLayout.setVerticalGroup(
                groupLayout.createParallelGroup(Alignment.LEADING)
                        .addGroup(groupLayout.createSequentialGroup()
                                .addGap(45)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(lblNewLabel)
                                        .addComponent(bookNameTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                        .addComponent(label)
                                        .addComponent(authorTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addGap(38)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(label_1)
                                        .addComponent(manJrb)
                                        .addComponent(femaleJrb)
                                        .addComponent(label_2)
                                        .addComponent(priceTxt, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addGap(31)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(lblNewLabel_1)
                                        .addComponent(bookTypeJcb, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                .addGap(36)
                                .addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
                                        .addComponent(label_3)
                                        .addComponent(bookDescTxt, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE))
                                .addGap(36)
                                .addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
                                        .addComponent(btnNewButton)
                                        .addComponent(btnNewButton_1))
                                .addContainerGap())
        );
        getContentPane().setLayout(groupLayout);

        bookDescTxt.setBorder(new LineBorder(new java.awt.Color(127,157,185), 1, false));
        fillBookType();
    }

    /**
     * 重置表单
     */
    private void resetValue(){
        this.bookNameTxt.setText("");
        this.authorTxt.setText("");
        this.manJrb.setSelected(true);
        this.priceTxt.setText("");
        if(this.bookTypeJcb.getItemCount()>0){
            this.bookTypeJcb.setSelectedIndex(0);
        }
        this.bookDescTxt.setText("");
    }

    /**
     * 图书添加
     * @param evt
     */
    private void bookAddActionPerformed(ActionEvent evt) throws Exception{
        String bookName=this.bookNameTxt.getText();
        String author=this.authorTxt.getText();
        String price=this.priceTxt.getText();
        String bookDesc=this.bookDescTxt.getText();

        if(StringUtil.isEmpty(bookName)){
            JOptionPane.showMessageDialog(null, "图书名称不能为空");
            return;
        }
        if(StringUtil.isEmpty(author)){
            JOptionPane.showMessageDialog(null, "图书作者不能为空");
            return;
        }
        if(StringUtil.isEmpty(price)){
            JOptionPane.showMessageDialog(null, "图书价格不能为空");
            return;
        }


        String sex="";
        if(manJrb.isSelected()){
            sex="男";
        }else if(femaleJrb.isSelected()){
            sex="女";
        }

        BookType bookType=(BookType) bookTypeJcb.getSelectedItem();
        int bookTypeId=bookType.getId();
        Book book=new Book(bookName,author,sex,Float.parseFloat(price),bookDesc,bookTypeId);
        Connection con=null;
        con=dbUtil.getCon();
        if(!bookType.isAvailable(con,book)){
            JOptionPane.showMessageDialog(null,"该图书类型不可用");
            int n=JOptionPane.showConfirmDialog(null,"是否重新启用该图书类型");
            if(n==0){
                try{
                    int addNum=bookDao.add(con, book);
                    if(addNum==1){
                        JOptionPane.showMessageDialog(null, "添加成功");
                        resetValue();
                    }else{
                        JOptionPane.showMessageDialog(null, "添加失败");
                    }
                }catch(Exception e2){
                    e2.printStackTrace();
                    JOptionPane.showMessageDialog(null, "添加失败");
                }finally{
                    try {
                        dbUtil.closeCon(con);
                    } catch (Exception e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();
                    }
                }
            }
            return;
        }
        try{
            int addNum=bookDao.add(con, book);
            if(addNum==1){
                JOptionPane.showMessageDialog(null, "添加成功");
                resetValue();
            }else{
                JOptionPane.showMessageDialog(null, "添加失败");
            }
        }catch(Exception e2){
            e2.printStackTrace();
            JOptionPane.showMessageDialog(null, "添加失败");
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
        }
    }

    /**
     * 重置事件
     * @param evt
     */
    private void resetValueActionPerformed(ActionEvent evt){
        this.resetValue();
    }
}